package com.zyx.maildemo.config.jwt;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: JWTFilter
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2019/7/27 13:18
 */
@Order(10000)
public class JWTFilter extends FormAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request,
                                      ServletResponse response,
                                      Object mappedValue) {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("token");
        if (StringUtils.isEmpty(token))
            token = req.getParameter("token");
        req.setAttribute("token", token);
        Subject subject = getSubject(request, response);
        try {
            subject.login(new JWTToken(token));
            return true;
        } catch (AuthenticationException e) {
            return false;
        }
    }
}
